package org.example.interceptor;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.util.JwtUtils;
import org.example.web.domain.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils  jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws IOException {
//        log.info("拦截器生效{}",request.getRequestURI());
        try {
            String token = request.getHeader("token");
            log.info("token = {}",token);
            Claims claims = jwtUtils.parseJwt(token);
            log.info("username = {}",claims.get("username"));
            return true;
        }catch (Exception e){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(Result.notLogin()));
            return false;
        }

    }
}
